package com.uphone.kingmall.main;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.china.zhuoyue.R;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.uphone.kingmall.activity.GoodsDetailActivity;
import com.uphone.kingmall.activity.HaggleGoodsListActivity;
import com.uphone.kingmall.activity.HomeCatListActivity;
import com.uphone.kingmall.activity.MyScanActivity;
import com.uphone.kingmall.activity.PinpaiListActivity;
import com.uphone.kingmall.activity.SearchGoodsListActivity;
import com.uphone.kingmall.activity.ShopDetailActivity;
import com.uphone.kingmall.activity.XianShiGouListActivity;
import com.uphone.kingmall.activity.YourLikeListActivity;
import com.uphone.kingmall.activity.personal.InviteCodeActivity;
import com.uphone.kingmall.activity.personal.ShangJiaRuZhuActivity;
import com.uphone.kingmall.activity.personal.ShangJiaRuZhuSuccessActivity;
import com.uphone.kingmall.activity.personal.VipBuyActivity;
import com.uphone.kingmall.activity.personal.VipUpgradeActivity;
import com.uphone.kingmall.adapter.HomeDaPaiAdapter;
import com.uphone.kingmall.adapter.HomeFenLeiAdapter;
import com.uphone.kingmall.adapter.HomeHaggleAdapter;
import com.uphone.kingmall.adapter.HomeQiangGouAdapter;
import com.uphone.kingmall.adapter.HomeYourLikeAdapter;
import com.uphone.kingmall.base.BaseFragment;
import com.uphone.kingmall.bean.AdvertsBean;
import com.uphone.kingmall.bean.FlashSalesListBean;
import com.uphone.kingmall.bean.GetShopStatusBean;
import com.uphone.kingmall.bean.GoodsListBean;
import com.uphone.kingmall.bean.IndexCatsList;
import com.uphone.kingmall.bean.RegisterAirBean;
import com.uphone.kingmall.bean.UserInfosBean;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.login.LoginActivity;
import com.uphone.kingmall.login.RegisterActivity;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.ConstansUtils;
import com.uphone.kingmall.utils.DialogUtil;
import com.uphone.kingmall.utils.GlideImageLoader;
import com.uphone.kingmall.utils.GlideRoundTransform;
import com.uphone.kingmall.utils.GlideUtils;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.RecycleViewDivider;
import com.uphone.kingmall.utils.SharedPreferencesHelper;
import com.uphone.kingmall.utils.ToastUtils;
import com.uphone.kingmall.utils.intent.IntentUtils;
import com.uphone.kingmall.utils.web.BaseWebActivity;
import com.uphone.kingmall.view.SnapUpCountDownTimerView;
import com.uphone.kingmall.view.dialog.RadishDialog;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * author : SuMeng
 * e-mail : 986335838@qq.com
 * time   : 2019/02/15
 * desc   : 首页fragment
 */
public class HomeFragment extends BaseFragment {

    @BindView(R.id.nested_scrollview)
    NestedScrollView nestedScrollview;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.banner_view)
    Banner bannerView;
    @BindView(R.id.iv_saoma)
    ImageView ivSaoma;
    @BindView(R.id.rl_sousuo)
    RelativeLayout rlSousuo;
    @BindView(R.id.iv_erweima)
    ImageView ivErweima;
    @BindView(R.id.iv_xiaoxi)
    ImageView ivXiaoxi;
    @BindView(R.id.rv_fenlei)
    RecyclerView rvFenlei;
    @BindView(R.id.timer_view)
    SnapUpCountDownTimerView rushBuyCountDownTimerView;
    @BindView(R.id.tv_qianggou_gengduo)
    TextView tvQianggouGengduo;
    @BindView(R.id.tv_haggle_gengduo)
    TextView tvHaggleduo;
    @BindView(R.id.rv_qianggou)
    RecyclerView rvQianggou;
    @BindView(R.id.rv_haggle)
    RecyclerView rvHaggle;
    @BindView(R.id.tv_dapai_gengduo1)
    TextView tvDapaiGengduo1;
    @BindView(R.id.rv_dapai1)
    RecyclerView rvDapai1;
    @BindView(R.id.iv_dapai1)
    ImageView ivDapai1;
    @BindView(R.id.tv_dapai_gengduo2)
    TextView tvDapaiGengduo2;
    @BindView(R.id.rv_dapai2)
    RecyclerView rvDapai2;
    @BindView(R.id.iv_dapai2)
    ImageView ivDapai2;
    @BindView(R.id.iv_banner)
    ImageView ivBanner;
    @BindView(R.id.shop_cart_refresh)
    SwipeRefreshLayout shopCartRefresh;
    @BindView(R.id.tv_tag)
    TextView tvTag;
    //    private ArrayList<String> strings;
    private ArrayList<IndexCatsList.CatsBean> catsList;
    private ArrayList<FlashSalesListBean.DataBean> flashSalesList;
    private ArrayList<GoodsListBean.DataBean> haggleList;
    private ArrayList<GoodsListBean.DataBean> pinpaiList;
    private ArrayList<GoodsListBean.DataBean> yourLikeList;
    private ArrayList<AdvertsBean.AdsBean> adsList;
    private HomeFenLeiAdapter homeFenLeiAdapter;
    private HomeQiangGouAdapter homeQiangGouAdapter;
    private HomeHaggleAdapter homeHaggleAdapter;
    private HomeDaPaiAdapter homeDaPaiAdapter;
    private HomeYourLikeAdapter homeYourLikeAdapter;
    private AdvertsBean.AdsBean midAdvertBean;
    private AdvertsBean.AdsBean bottomAdvertBean;
    private int shopStatusInt;
    private UserInfosBean.UserInfoBean user;

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_fragment_home;
    }

    @Override
    public void initData() {
        // 初始化recycleview
        initQiangGou();
        initHaggle();
        initFenLei();
        initDaPai();
        nestedScrollview.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView nestedScrollView, int i, int i1, int i2, int i3) {
                if (px2dp(getActivity(), i1) > 180) {
                    llTitle.setBackgroundColor(getResources().getColor(R.color.colorTextSelect));
                    tvTag.setTextColor(getResources().getColor(R.color.colorTextSelect));
                    tvTag.setBackground(getResources().getDrawable(R.drawable.shape_tag));
                } else {
                    llTitle.setBackgroundColor(getResources().getColor(R.color.colorTransparent));
                    tvTag.setTextColor(getResources().getColor(R.color.white));
                    tvTag.setBackground(getResources().getDrawable(R.drawable.shape_tag1));
                }
            }
        });

        shopCartRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shopCartRefresh.setRefreshing(false);
                    }
                }, 2000);
                loadData();
            }
        });

        loadData();
        rushBuyCountDownTimerView.setOnFinishListener(new SnapUpCountDownTimerView.FinishListener() {
            @Override
            public void onFinish() {
                // 重新倒计时
                startDownTimer();
            }
        });
    }

    private void initHaggle() {
        rvHaggle.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        rvHaggle.addItemDecoration(new RecycleViewDivider(getActivity(),
                LinearLayoutManager.VERTICAL, SizeUtils.dp2px(0.5f), Color.parseColor("#eeeeee")));
//        rvQianggou.addItemDecoration(new RecycleViewDivider(getActivity(),
//                LinearLayoutManager.HORIZONTAL,SizeUtils.dp2px(0.5f), Color.parseColor("#eeeeee")));
        homeHaggleAdapter = new HomeHaggleAdapter(getActivity());
        rvHaggle.setAdapter(homeHaggleAdapter);
        homeHaggleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                IntentUtils.getInstance().with(getActivity(), GoodsDetailActivity.class)
                        .putInt(ConstansUtils.ID, haggleList.get(position).getGoodsId())
                        .putInt(ConstansUtils.TYPE, GoodsDetailActivity.TYPE_HAGGLE).start();
            }
        });
    }


    @Override
    public void loadJPush() {
        super.loadJPush();
        getUserInfo();
    }

    @Override
    public void onResume() {
        super.onResume();
        getUserInfo();
        // 抢购倒计时及获取抢购数据
        startDownTimer();
    }

    private void getUserInfo() {
        if (!TextUtils.isEmpty(SharedPreferencesHelper.getToken())) {
            OkGoUtils.normalRequest(MyUrl.getUserInfo, null, new onNormalRequestListener() {
                @Override
                public void onSuccess(String body, int code) {
                    if (code == 0) {
                        try {
                            UserInfosBean bean = GsonUtils.getGson().fromJson(body, UserInfosBean.class);
                            user = bean.getUserInfo();
                            if (user != null) {
                                if (tvTag == null)
                                    return;
                                if (user.getCollectmsgCount() > 0) {
                                    tvTag.setVisibility(View.VISIBLE);
                                    tvTag.setText(user.getCollectmsgCount() + "");
                                } else {
                                    tvTag.setVisibility(View.GONE);
                                }
                                shopStatusInt = user.getShopStatus();
                            } else {
                            }
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onError(Response<String> response) {

                }
            });
        }
    }

    private void loadData() {
        loadBannerData(1);
        loadBannerData(2);
        loadBannerData(3);

        loadRvData();
        // 抢购倒计时及获取抢购数据
        startDownTimer();
    }

    private void loadRvData() {

        OkGoUtils.normalRequest(MyUrl.getIndexCats, null, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                final IndexCatsList catsListBean = GsonUtils.getGson().fromJson(body, IndexCatsList.class);
                if (catsListBean.getCode() == 0) {
                    if (catsList == null) {
                        catsList = new ArrayList<>();
                    }
                    catsList.clear();
                    catsList.add(new IndexCatsList.CatsBean("砍价购"));
                    if (catsListBean.getCats() != null) {
                        catsList.addAll(CommonUtil.getList(catsListBean.getCats(), 8));
                    }
                    catsList.add(new IndexCatsList.CatsBean("票务中心"));
                    homeFenLeiAdapter.setNewData(catsList);
                }
            }

            @Override
            public void onError(Response<String> response) {
            }
        });


        HttpParams params = new HttpParams();
        params.put("page", "1");
        params.put("limit", "10");
        params.put("orderby", "1");
        params.put("asc", "2");

        OkGoUtils.normalRequest(MyUrl.getPinpaiGoods, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                final GoodsListBean bean = GsonUtils.getGson().fromJson(body, GoodsListBean.class);
                if (bean.getCode() == 0) {
                    if (pinpaiList == null) {
                        pinpaiList = new ArrayList<>();
                    }
                    pinpaiList.clear();
                    if (bean.getData() != null) {
                        pinpaiList.addAll(bean.getData());
                    }
                    homeDaPaiAdapter.setNewData(pinpaiList);
                }
            }

            @Override
            public void onError(Response<String> response) {
            }
        });
        params.put("limit", "10");
        OkGoUtils.normalRequest(MyUrl.getYourLikes, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                final GoodsListBean bean = GsonUtils.getGson().fromJson(body, GoodsListBean.class);
                if (bean.getCode() == 0) {
                    if (yourLikeList == null) {
                        yourLikeList = new ArrayList<>();
                    }
                    yourLikeList.clear();
                    if (bean.getData() != null) {
                        yourLikeList.addAll(bean.getData());
                    }
                    homeYourLikeAdapter.setNewData(yourLikeList);
                }
            }

            @Override
            public void onError(Response<String> response) {
            }
        });

        // 获取网络数据
        params.put("limit", "10");
        params.put("isIndex", "1");
        OkGoUtils.normalRequest(MyUrl.getHaggleGoods, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                final GoodsListBean catsListBean = GsonUtils.getGson().fromJson(body, GoodsListBean.class);
                if (haggleList == null) {
                    haggleList = new ArrayList<>();
                }
                haggleList.clear();
                if (catsListBean.getCode() == 0) {
                    if (catsListBean.getData() != null) {
                        haggleList.addAll(CommonUtil.getList(catsListBean.getData(), 8));
                    }
                }
                homeHaggleAdapter.setNewData(haggleList);
            }

            @Override
            public void onError(Response<String> response) {
            }
        });
    }

    private void startDownTimer() {
        Date myDate = new Date();
        int minutes = myDate.getMinutes() + 1;
        int seconds = myDate.getSeconds() + 1;
        if (minutes > 60) {
            minutes = 60;
        }
        if (seconds > 60) {
            seconds = 60;
        }
        rushBuyCountDownTimerView.setTime(0, 60 - minutes, 60 - seconds);//设置小时，分钟，秒。注意不能大于正常值，否则会抛出异常
        rushBuyCountDownTimerView.start();//开始倒计时
        HttpParams params = new HttpParams();
        params.put("isIndex", "1");
        params.put("page", "1");
        params.put("limit", "8");

        // 获取网络数据
        OkGoUtils.normalRequest(MyUrl.getFlashSales, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                final FlashSalesListBean catsListBean = GsonUtils.getGson().fromJson(body, FlashSalesListBean.class);
                if (flashSalesList == null) {
                    flashSalesList = new ArrayList<>();
                }
                flashSalesList.clear();
                if (catsListBean.getCode() == 0) {
                    if (catsListBean.getData() != null) {
                        flashSalesList.addAll(CommonUtil.getList(catsListBean.getData(), 8));
                    }
                }
                homeQiangGouAdapter.setNewData(flashSalesList);
            }

            @Override
            public void onError(Response<String> response) {
            }
        });

    }

    private void loadBannerData(final int type) {
        HttpParams params = new HttpParams();
        params.put("type", type + "");
        OkGoUtils.normalRequest(MyUrl.adverts, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                final AdvertsBean bean = GsonUtils.getGson().fromJson(body, AdvertsBean.class);
                if (bean.getCode() == 0) {
                    if (type == 1) {
                        if (adsList == null) {
                            adsList = new ArrayList<>();
                        }
                        adsList.clear();
                        if (bean.getAds() != null && bean.getAds().size() > 0) {
                            adsList.addAll(bean.getAds());
                            ivBanner.setVisibility(View.GONE);
                        }
                        initBanner(adsList);
                    } else if (type == 2) {
                        //中部图片
                        if (bean.getAds() != null && bean.getAds().size() > 0) {
                            midAdvertBean = bean.getAds().get(0);
                            RoundedCorners roundedCorners = new RoundedCorners(SizeUtils.dp2px(8));
                            RequestOptions requestOptions = RequestOptions
                                    .bitmapTransform(roundedCorners)
                                    .placeholder(R.mipmap.img_default_wz)
                                    .error(R.mipmap.img_default_wz)
                                    .transform(new GlideRoundTransform(getActivity(), SizeUtils.dp2px(8)));
                            GlideUtils.getInstance().loadImage(getActivity(), midAdvertBean.getAdImg(), ivDapai1, requestOptions);

//                            GlideUtils.getInstance().loadCornerImage(getActivity(), midAdvertBean.getAdImg(), SizeUtils.dp2px(8), ivDapai1);
                            if (ivDapai1 != null) {
                                ivDapai1.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        if (midAdvertBean.getGoodsId() > 0) {
                                            IntentUtils.getInstance()
                                                    .with(getActivity(), GoodsDetailActivity.class)
                                                    .putInt(ConstansUtils.ID, midAdvertBean.getGoodsId())
                                                    .putInt(ConstansUtils.TYPE, GoodsDetailActivity.TYPE_ADVERTS)
                                                    .start();
                                        }
                                    }
                                });
                            }
                        }
                    } else {
                        //底部图片
                        if (bean.getAds() != null && bean.getAds().size() > 0) {
                            bottomAdvertBean = bean.getAds().get(0);
                            RoundedCorners roundedCorners = new RoundedCorners(SizeUtils.dp2px(8));
                            RequestOptions requestOptions = RequestOptions
                                    .bitmapTransform(roundedCorners)
                                    .placeholder(R.mipmap.img_default_wz)
                                    .error(R.mipmap.img_default_wz)
                                    .transform(new GlideRoundTransform(getActivity(), SizeUtils.dp2px(8)));
                            GlideUtils.getInstance().loadImage(getActivity(), bottomAdvertBean.getAdImg(), ivDapai2, requestOptions);
                            if (ivDapai2 != null) {
                                ivDapai2.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        if (CommonUtil.checkLogin()) {
                                            if (shopStatusInt == 1) {
                                                //商家已入驻
                                                CommonUtil.startIntent(getActivity(), ShangJiaRuZhuSuccessActivity.class);
                                            } else {
                                                GetShopStatus();
                                            }
                                        }
                                    }
                                });
                            }
                        }
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
            }
        });
    }

    private void GetShopStatus() {
        OkGoUtils.normalRequestGet(MyUrl.GetShopStatus, new onNormalRequestListener() {
            @Override
            public void onSuccess(String json, int code) {
                if (code == 0) {
                    GetShopStatusBean bean = GsonUtils.getGson().fromJson(json, GetShopStatusBean.class);
                    if (bean.getCode() == 0) {
                        if (bean.getData().getShopStatus() == 1) {
                            openActivity(ShangJiaRuZhuSuccessActivity.class);
                        } else if (bean.getData().getShopStatus() == 4) {
                            if (user.getUserType() == 2) {
                                if (user.getWay() == 1) {
                                    Bundle bundle = new Bundle();
                                    bundle.putInt("type", 3);
                                    openActivity(VipUpgradeActivity.class, bundle);
                                } else {
                                    openActivity(VipUpgradeActivity.class);
                                }
                            } else {
                                openActivity(ShangJiaRuZhuActivity.class);
                            }
                        } else {
                            openActivity(ShangJiaRuZhuActivity.class);
                        }
                    } else if (bean.getCode() == 101 || bean.getCode() == 102) {
                        if (user.getWay() == 0) {
                            Bundle bundle = new Bundle();
                            bundle.putInt("type", 3);
                            openActivity(VipBuyActivity.class, bundle);
                        } else if (user.getWay() == 1) {
                            Bundle bundle = new Bundle();
                            bundle.putInt("type", 3);
                            openActivity(VipUpgradeActivity.class, bundle);
                        } else {
                            openActivity(VipUpgradeActivity.class);
                        }
                    }

                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private void initDaPai() {

        rvDapai1.setLayoutManager(new GridLayoutManager(getActivity(), 2));

        homeDaPaiAdapter = new HomeDaPaiAdapter();
        rvDapai1.setAdapter(homeDaPaiAdapter);
        rvDapai2.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        homeYourLikeAdapter = new HomeYourLikeAdapter();
        rvDapai2.setAdapter(homeYourLikeAdapter);
        homeDaPaiAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                IntentUtils.getInstance()
                        .with(getActivity(), GoodsDetailActivity.class)
                        .putInt(ConstansUtils.ID, pinpaiList.get(position).getGoodsId())
                        .start();
//                openActivity(GoodsDetailActivity.class);
            }
        });
        homeYourLikeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                IntentUtils.getInstance()
                        .with(getActivity(), GoodsDetailActivity.class)
                        .putInt(ConstansUtils.ID, yourLikeList.get(position).getGoodsId())
                        .start();
//                openActivity(GoodsDetailActivity.class);
            }
        });

    }

    //将px转换为dp
    public static int px2dp(Context context, int pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    private void initQiangGou() {
        rvQianggou.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        rvQianggou.addItemDecoration(new RecycleViewDivider(getActivity(),
                LinearLayoutManager.VERTICAL, SizeUtils.dp2px(0.5f), Color.parseColor("#eeeeee")));
//        rvQianggou.addItemDecoration(new RecycleViewDivider(getActivity(),
//                LinearLayoutManager.HORIZONTAL,SizeUtils.dp2px(0.5f), Color.parseColor("#eeeeee")));
        homeQiangGouAdapter = new HomeQiangGouAdapter(getActivity());
        rvQianggou.setAdapter(homeQiangGouAdapter);
        homeQiangGouAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                IntentUtils.getInstance().with(getActivity(), GoodsDetailActivity.class)
                        .putInt(ConstansUtils.ID, flashSalesList.get(position).getGoodsId())
                        .putInt(ConstansUtils.TYPE, GoodsDetailActivity.TYPE_FLASH).start();
            }
        });
    }

    /**
     * 初始化分类
     */
    private void initFenLei() {
        rvFenlei.setLayoutManager(new GridLayoutManager(getActivity(), 5));
        rvFenlei.addItemDecoration(new RecycleViewDivider(
                getActivity(), LinearLayoutManager.HORIZONTAL, 10, getResources().getColor(R.color.colorBg)));
        homeFenLeiAdapter = new HomeFenLeiAdapter();
        rvFenlei.setAdapter(homeFenLeiAdapter);

        homeFenLeiAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position == 0) {
                    Intent intent = new Intent(getActivity(), HaggleGoodsListActivity.class);
                    startActivity(intent);
                } else if (position == 9) {
                    if (TextUtils.isEmpty(SharedPreferencesHelper.getToken())) {
                        CommonUtil.startIntent(getActivity(), LoginActivity.class);
                        return;
                    }
                    RegisterAir(user.getUserMobile());

                } else {
                    IntentUtils.getInstance().with(getActivity(), HomeCatListActivity.class)
                            .putInt(ConstansUtils.ID, catsList.get(position).getId())
                            .putString(ConstansUtils.TITLE, catsList.get(position).getCatName())
                            .putString(ConstansUtils.URL, MyUrl.getCatGoods).start();
                }
            }
        });
    }

    @Override
    public void initView(View view) {
        initImmersionBar();
    }


    /**
     * 设置banner数据
     *
     * @param topBannerList
     */
    private void initBanner(final ArrayList<AdvertsBean.AdsBean> topBannerList) {

        List images = new ArrayList<>();
        for (AdvertsBean.AdsBean bean : topBannerList) {
            images.add(bean.getAdImg());
        }

        bannerView.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                LogUtils.e("点击banner");
                if (topBannerList.get(position).getGoodsId() > 0) {
                    IntentUtils.getInstance()
                            .with(getActivity(), GoodsDetailActivity.class)
                            .putInt(ConstansUtils.ID, topBannerList.get(position).getGoodsId())
                            .putInt(ConstansUtils.TYPE, GoodsDetailActivity.TYPE_ADVERTS)
                            .start();
                }
            }
        });
        //设置图片加载器
        bannerView.setImageLoader(new GlideImageLoader());
        //不显示指示器和标题
        bannerView.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片集合
        bannerView.setImages(images);
        //banner设置方法全部调用完毕时最后调用
        bannerView.start();
    }

    @OnClick({R.id.iv_saoma, R.id.rl_sousuo, R.id.iv_erweima, R.id.iv_xiaoxi, R.id.tv_haggle_gengduo, R.id.tv_qianggou_gengduo, R.id.tv_dapai_gengduo1, R.id.iv_dapai1, R.id.tv_dapai_gengduo2, R.id.iv_dapai2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_saoma:
                //扫一扫
                ScanForErCode();
                break;
            case R.id.rl_sousuo:
                startActivity(new Intent(getActivity(), SearchGoodsListActivity.class));
                break;
            case R.id.iv_erweima://我的推荐码
                if (CommonUtil.checkLogin()) {
                    IntentUtils.getInstance().with(getActivitySafely(), InviteCodeActivity.class).putString(ConstansUtils.URL, MyUrl.h5AppDownload).start();
                }
                break;
            case R.id.iv_xiaoxi:
//                if (TextUtils.isEmpty(SharedPreferencesHelper.getToken())) {
//                    CommonUtil.startIntent(getActivity(), LoginActivity.class);
//                    return;
//                }
//                IntentUtils.getInstance().with(getActivity(), MessageActivity.class)
//                        .putInt("msgCount", user.getCollectmsgCount())
//                        .start();
                break;
            case R.id.tv_haggle_gengduo:
                startActivity(new Intent(getActivity(), HaggleGoodsListActivity.class));
                break;
            case R.id.tv_qianggou_gengduo:
                startActivity(new Intent(getActivity(), XianShiGouListActivity.class));
                break;
            case R.id.tv_dapai_gengduo1:
                CommonUtil.startIntent(getActivity(), PinpaiListActivity.class);
                break;
            case R.id.iv_dapai1:
                break;
            case R.id.tv_dapai_gengduo2:
                CommonUtil.startIntent(getActivity(), YourLikeListActivity.class);
                break;
            case R.id.iv_dapai2:
                break;
        }
    }

    /**
     * 扫一扫权限
     */
    private void ScanForErCode() {
        if (Build.VERSION.SDK_INT > 22) {
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.CAMERA}, 2);
            } else {
                StartScanErCode();
            }
        } else {
            StartScanErCode();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults != null && grantResults.length != 0) {
            if (requestCode == 2) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    StartScanErCode();
                } else {
                    DialogUtil.openAppDetails(getActivity(), "相机");
                }
            }
        }
    }

    void StartScanErCode() {
        Intent intent = new Intent(getActivity(), MyScanActivity.class);
        startActivityForResult(intent, 1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            // 扫一扫
            if (data != null) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    LogUtils.e("扫一扫解析结果是：" + result);
                    if (TextUtils.isEmpty(result)) {
                        return;
                    }
                    final String[] split = result.split("/");
                    if (split == null || split.length == 0) {
                        return;
                    }
                    final String endStr = split[split.length - 1];
                    if (result.startsWith(ConstansUtils.QRCodeShop)) {
                        // 店铺详情
                        try {
                            int shopId = Integer.parseInt(endStr);
                            CommonUtil.startIntent(getActivity(), ShopDetailActivity.class, shopId);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else if (result.startsWith(ConstansUtils.QRCodeOrderCheck)) {
                        // 到店订单
                        CommonUtil.showAlterDialog(getActivity(), "确定核销此订单？", new CommonUtil.OnAlterDialogCallBack() {
                            @Override
                            public void callBack(RadishDialog dialog, View view) {
                                HttpParams params = new HttpParams();
                                params.put("checkCode", endStr);
                                CommonUtil.submitNet(getActivity(), MyUrl.checkOrder, params, "核销成功！");
                            }
                        });
                    } else if (result.startsWith(ConstansUtils.QRCodeUserInvite)) {
                        //用户推荐码
                        if (!TextUtils.isEmpty(SharedPreferencesHelper.getToken())) {
                            ToastUtils.showShortToast(getActivity(), "您以登录");
                        } else {
                            IntentUtils.getInstance().with(getActivity(), RegisterActivity.class).putString("invite", endStr).start();
                        }
                    } else if (TextUtils.equals(result, MyUrl.h5AppDownload)) {
//                        IntentUtils.getInstance().with(getActivitySafely(), BaseWebActivity.class)
//                                .putString(ConstansUtils.TITLE, "王者商城")
//                                .putString(ConstansUtils.URL, MyUrl.h5AppDownload)
//                                .start();

                        Uri uri = Uri.parse(MyUrl.h5AppDownload);
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.VIEW");
                        intent.setData(uri);
                        startActivity(intent);
                    }
                }
            }
        }
    }


    private void RegisterAir(String mobile) {
        HttpParams params = new HttpParams();
        params.put("mobile", mobile);
        OkGoUtils.progressRequest(MyUrl.RegisterAir, getActivity(), params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 0) {
                    RegisterAirBean registerAirBean = GsonUtils.getGson().fromJson(body, RegisterAirBean.class);
                    String key = "m8datwl29bs029kclrk1";

                    String sign = md5(registerAirBean.getData().getHyid() + registerAirBean.getData().getZcm() + key);
                    Uri uri = Uri.parse(MyUrl.h5ShenZhenAir + "sign=" + sign + "&hyid=" + registerAirBean.getData().getHyid() + "&zcm=" + registerAirBean.getData().getZcm());
                    Intent intent = new Intent(getActivity(), BaseWebActivity.class);
//                    intent.setAction("android.intent.action.VIEW");
//                    intent.setData(uri);
                    intent.putExtra("title","");
                    intent.putExtra("url",MyUrl.h5ShenZhenAir + "sign=" + sign + "&hyid=" + registerAirBean.getData().getHyid() + "&zcm=" + registerAirBean.getData().getZcm());
                    startActivity(intent);


                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    @NonNull
    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}
